import React from 'react';

export default class App extends React.Component {
  // 1. 声明state. currentUrl
  state = {
    currentUrl: '/home',
  };
  // 2. 条件渲染

  componentDidMount() {
    // 4. 挂载后，直接修改url为最新值
    const url = window.location.hash.slice(1);
    this.setState({ currentUrl: url });

    // 3. 监听url变化 ，更新状态
    window.addEventListener('hashchange', () => {
      const url = window.location.hash.slice(1);
      this.setState({ currentUrl: url });
    });
  }

  render() {
    const { currentUrl } = this.state;
    return (
      <div>
        <h1>app组件</h1>
        <ul>
          <li>
            <a href="#/home">首页</a>
          </li>
          <li>
            <a href="#/my">我的音乐</a>
          </li>
          <li>
            <a href="#/friend">我的朋友</a>
          </li>
        </ul>
        {currentUrl === '/home' && <Home></Home>}
        {currentUrl === '/my' && <MyMusic></MyMusic>}
        {currentUrl === '/friend' && <Friend></Friend>}
      </div>
    );
  }
}

function Home() {
  return <h1>我是首页组件</h1>;
}

function MyMusic() {
  return <h1>我是我的音乐件</h1>;
}

function Friend() {
  return <h1>我是朋友组件</h1>;
}
